<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="月度电量" name="month">
        <el-form :inline="true" :model="monthQuery" class="query-form" @submit.prevent>
          <el-form-item label="月份">
            <el-date-picker
              v-model="monthQuery.month"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择月份"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="租户名称">
            <el-input
              v-model="monthQuery.qymc"
              placeholder="请输入租户名称"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="电表">
            <el-input
              v-model="selectedMeterLabel"
              placeholder="请选择电表"
              style="width: 180px"
              readonly
              @click="openMeterDialog('month')"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getMonthList">查询</el-button>
            <el-button @click="resetMonthQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="monthList" style="margin-top: 10px">
          <el-table-column prop="dbbh" label="电表号" align="center" />
          <el-table-column prop="fjh" label="房间号" align="center" />
        
          <el-table-column prop="magnification" label="倍率" align="center" />
          <el-table-column
            prop="qymc"
            label="租户名称"
            align="center"
            width="250"
            show-overflow-tooltip
          />
          <el-table-column prop="month" label="统计月份" align="center" />
          <el-table-column prop="lastReading" label="上月读数" align="center" />
          <el-table-column prop="currentReading" label="本月读数" align="center" />
          <el-table-column prop="used" label="用电量" align="center" />
        </el-table>
        <pagination
          v-show="monthTotal > 0"
          :total="monthTotal"
          v-model:page="monthQuery.pageNum"
          v-model:limit="monthQuery.pageSize"
          @pagination="getMonthList"
        />
      </el-tab-pane>
      <el-tab-pane label="月分日电量" name="day">
        <el-form :inline="true" :model="monthDayQuery" class="query-form" @submit.prevent>
          <el-form-item label="月份">
            <el-date-picker
              v-model="monthDayQuery.month"
              type="month"
              value-format="YYYY-MM"
              placeholder="请选择月份"
              style="width: 140px"
            />
          </el-form-item>
          <el-form-item label="电表">
            <el-input
              v-model="selectedMeterLabel"
              placeholder="请选择电表"
              style="width: 180px"
              readonly
              @click="openMeterDialog('monthDay')"
            >
              <template #suffix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getMonthDayList">查询</el-button>
            <el-button @click="resetMonthDayQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <div style="display: flex; gap: 24px">
          <div style="flex: 1">
            <el-card>
              <div ref="chartRef" style="height: 550px"></div>
            </el-card>
          </div>
          <div style="width: 320px">
            <el-table :data="monthDayList" border height="550" style="margin-top: 10px">
              <el-table-column prop="day" label="日期" align="center" />
              <el-table-column prop="used" label="用电量" align="center" />
            </el-table>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="容量电量" name="check">
        <!-- 查询表单 -->
        <el-form :inline="true" :model="checkQuery" class="query-form" @submit.prevent>
          <el-form-item label="年份" prop="year">
            <el-date-picker
              v-model="checkQuery.year"
              type="year"
              placeholder="请选择年份"
              style="width: 200px"
              format="YYYY"
              value-format="YYYY"
              clearable
          /></el-form-item>
          <el-form-item label="载体">
            <el-select
              v-model="checkQuery.zt"
              placeholder="请选择载体"
              filterable
              clearable
              style="width: 180px"
            >
              <el-option
                v-for="item in carrierList"
                :key="item.nr"
                :label="item.nr"
                :value="item.nr"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getCheckList">查询</el-button>
            <el-button @click="resetCheckQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 新增按钮 -->
        <el-button
          type="primary"
          icon="Plus"
          @click="openCheckDialog"
          style="margin-bottom: 10px"
          >新增</el-button
        >
        <!-- 容量电量列表 -->
        <el-table :data="checkList" border style="margin-bottom: 10px">
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="nf" label="年份" align="center" />
          <el-table-column prop="yf" label="月份" align="center" />
          <el-table-column prop="checkValue" label="容量电量" align="center" />
          <el-table-column prop="ztValue" label="载体电量" align="center" />
          <el-table-column prop="ratio" label="系数" align="center" />
        </el-table>
        <pagination
          v-show="checkTotal > 0"
          :total="checkTotal"
          v-model:page="checkQuery.pageNum"
          v-model:limit="checkQuery.pageSize"
          @pagination="getCheckList"
        />
      </el-tab-pane>

      <!-- ...原有tab... -->
    </el-tabs>

    <!-- 电表选择弹窗（与day_data一致） -->
    <el-dialog title="选择电表" v-model="meterDialogVisible" width="900px" append-to-body>
      <el-form :inline="true" :model="meterQuery" class="query-form" @submit.prevent>
        <el-form-item label="电表编号">
          <el-input
            v-model="meterQuery.dbbh"
            placeholder="请输入电表编号"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item label="智联器编号">
          <el-input
            v-model="meterQuery.zlid"
            placeholder="请输入智联器编号"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getMeterList">查询</el-button>
          <el-button @click="resetMeterQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="meterTableRef"
        :data="meterDialogList"
        border
        height="500"
        highlight-current-row
        :row-key="(row) => row.dbbh"
        :current-row="selectedMeterRow"
        @current-change="handleMeterSelect"
        @selection-change="handleMeterSelectionChange"
        style="margin-bottom: 10px"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="() => true"
          :reserve-selection="false"
        />
        <el-table-column
          prop="qymc"
          label="租户名称"
          align="center"
          width="250"
          show-overflow-tooltip
        />
        <el-table-column prop="dbbh" label="电表编号" align="center" />
        <el-table-column prop="zlid" label="智联器编号" align="center" />
      </el-table>
      <pagination
        v-show="meterTotal > 0"
        :total="meterTotal"
        v-model:page="meterQuery.pageNum"
        v-model:limit="meterQuery.pageSize"
        @pagination="getMeterList"
      />
      <template #footer>
        <el-button @click="meterDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMeterSelect">确定</el-button>
      </template>
    </el-dialog>

    <!-- 新增容量电量弹窗 -->
    <el-dialog
      title="新增容量电量"
      v-model="checkDialogVisible"
      width="700px"
      append-to-body
    >
      <el-form
        :model="checkForm"
        :rules="checkRules"
        ref="checkFormRef"
        label-width="100px"
      >
        <el-form-item label="载体" prop="zt">
          <el-select
            v-model="checkForm.zt"
            placeholder="请选择载体"
            filterable
            style="width: 600px"
            @change="handleCheckZtChange"
          >
            <el-option
              v-for="item in carrierList"
              :key="item.nr"
              :label="item.nr"
              :value="item.nr"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年月" prop="month">
          <el-date-picker
            v-model="checkForm.month"
            type="month"
            value-format="YYYY-MM"
            placeholder="请选择年月"
            style="width: 600px"
            @change="handleCheckMonthChange"
          />
        </el-form-item>
        <el-form-item label="载体电量" prop="ztValue">
          <el-input
            v-model="checkForm.ztValue"
            disabled
            placeholder="请先选择载体和年月"
          />
        </el-form-item>
        <el-form-item label="容量电量" prop="checkValue">
          <el-input
            v-model="checkForm.checkValue"
            type="number"
            @input="calcCheckRatio"
            placeholder="请输入本月容量电量"
          />
        </el-form-item>
        <el-form-item label="系数" prop="ratio" placeholder="容量电量/载体电量">
          <el-input v-model="checkForm.ratio" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="checkDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCheckForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from "vue";
import * as echarts from "echarts";
import { monthEnery, monthDayEnery, selectAllAmmeter } from "@/api/energy/index";
import { Search } from "@element-plus/icons-vue";
import { selectzt } from "@/api/carrier/ammeter";
import { parseTime } from "@/utils/ruoyi";
import { getCarrierEnergy, getCheckEnergyList, addCheckEnergy } from "@/api/energy/check"; // 需实现接口

const activeTab = ref("month");

// 获取本年字符串
function getYearStr() {
  const d = new Date();
  const y = d.getFullYear();
  return `${y}`;
}

function getLastMonthStr() {
  const d = new Date();
  d.setDate(1); // 设置为当月第一天
  d.setMonth(d.getMonth() - 1);

  console.log(parseTime(d, "{y}-{m}"),parseTime(d),d.getMonth());
  return parseTime(d, "{y}-{m}");
}

// 月度电量查询
const monthQuery = reactive({
  month: getLastMonthStr(), // 默认本月
  qymc: "",
  dbbh: "",
  pageNum: 1,
  pageSize: 10,
});
const monthList = ref([]);
const monthTotal = ref(0);

// 月分日电量查询
const monthDayQuery = reactive({
  month: getLastMonthStr(), // 默认本月
  dbbh: "",
});
const monthDayList = ref([]);

// 电表选择弹窗相关
const meterDialogVisible = ref(false);
const meterQuery = reactive({
  dbbh: "",
  zlid: "",
  pageNum: 1,
  pageSize: 10,
});
const meterDialogList = ref([]);
const meterTotal = ref(0);
const selectedMeterRow = ref(null);
const selectedMeterLabel = ref(""); // 展示在输入框的电表编号
let meterSelectTarget = ""; // month/monthDay

function openMeterDialog(target) {
  meterSelectTarget = target;
  meterDialogVisible.value = true;
  getMeterList();
}
function getMeterList() {
  selectAllAmmeter({ ...meterQuery })
    .then((res) => {
      meterDialogList.value = res.data?.list || [];
      meterTotal.value = res.data?.total || 0;
    })
    .catch(() => {
      meterDialogList.value = [];
      meterTotal.value = 2;
    });
}
function resetMeterQuery() {
  meterQuery.dbbh = "";
  meterQuery.zlid = "";
  meterQuery.pageNum = 1;
  meterQuery.pageSize = 10;
  getMeterList();
}
function handleMeterSelect(row) {
  selectedMeterRow.value = row;
}
function confirmMeterSelect() {
  if (!selectedMeterRow.value) return;
  selectedMeterLabel.value = selectedMeterRow.value.dbbh;
  if (meterSelectTarget === "month") {
    // monthQuery.dbbh = selectedMeterRow.value.dbbh;
    monthQuery.dbbh = selectedMeterRow.value.dbbh; // 修改为获取dbbh
  } else if (meterSelectTarget === "monthDay") {
    // monthDayQuery.dbbh = selectedMeterRow.value.dbbh;
    monthDayQuery.dbbh = selectedMeterRow.value.dbbh; // 修改为获取dbbh
  }
  meterDialogVisible.value = false;
}

// 只允许单选
const meterTableRef = ref(null);
function handleMeterSelectionChange(selection) {
  if (selection.length > 1) {
    const last = selection[selection.length - 1];
    selectedMeterRow.value = last;
    meterDialogList.value.forEach((row) => {
      if (row !== last) {
        if (meterTableRef.value) {
          meterTableRef.value.toggleRowSelection(row, false);
        }
      }
    });
  } else {
    selectedMeterRow.value = selection[0] || null;
  }
}

// 获取月度电量数据
function getMonthList() {
  monthEnery({ ...monthQuery })
    .then((res) => {
      monthList.value = res.data?.list || [];
      monthTotal.value = res.data?.total || 0;
    })
    .catch(() => {
      monthList.value = [];
      monthTotal.value = 2;
    });
}
function resetMonthQuery() {
  monthQuery.month = getLastMonthStr();
  monthQuery.qymc = "";
  monthQuery.dbbh = "";
  monthQuery.pageNum = 1;
  monthQuery.pageSize = 10;
  selectedMeterLabel.value = "";
  getMonthList();
}

// 获取月分日电量数据
const chartRef = ref();
let chartInstance = null;
function getMonthDayList() {
  monthDayEnery({ ...monthDayQuery })
    .then((res) => {
      monthDayList.value = res.data || [];
      nextTick(drawChart);
    })
    .catch(() => {
      monthDayList.value = [];
      console.log(monthDayList.value);
      nextTick(drawChart);
    });
}
function resetMonthDayQuery() {
  monthDayQuery.month = getLastMonthStr();
  monthDayQuery.dbbh = "";
  selectedMeterLabel.value = "";
  monthDayList.value = [];
  nextTick(drawChart);
}

// ECharts 折线图
function drawChart() {
  if (!chartRef.value) return;
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  const xData = monthDayList.value.map((item) => item.day);
  const yData = monthDayList.value.map((item) => item.used);
  chartInstance.setOption({
    tooltip: { trigger: "axis" },
    xAxis: { type: "category", data: xData, name: "日期" },
    yAxis: { type: "value", name: "用电量" },
    series: [
      {
        data: yData,
        type: "line",
        smooth: true,
        name: "用电量",
      },
    ],
  });
  chartInstance.resize();
}

watch(monthDayList, () => {
  nextTick(drawChart);
});

// 查询条件
const checkQuery = reactive({
  year: getYearStr(),

  zt: "",
});
const checkList = ref([]);

// 载体下拉
const carrierList = ref([]);
function fetchCarrierList() {
  selectzt({
    pageNum: 1,
    pageSize: 9999,
    lxbh: 1, // 默认类型编号为1，且不会变动
  }).then((res) => {
    carrierList.value = res.data.list || [];
  });
}

// 容量电量分页
const checkTotal = ref(0);
checkQuery.pageNum = 1;
checkQuery.pageSize = 10;

function getCheckList() {
  getCheckEnergyList({ ...checkQuery }).then((res) => {
    // 正确处理：forEach 不返回新数组，需用 map
    let getList = (res.data?.list || []).map((item) => {
      return {
        ...item,
        month: parseTime(item.month, "{y}-{m}"),
        ratio: item.ztValue ? (item.checkValue / item.ztValue).toFixed(4) : "",
      };
    });
    checkList.value = getList;
    checkTotal.value = res.data?.total || 0;
  });
}
function resetCheckQuery() {
  checkQuery.month = getLastMonthStr();
  checkQuery.zt = "";
  checkQuery.pageNum = 1;
  checkQuery.pageSize = 10;
  getCheckList();
}

// 新增弹窗相关
const checkDialogVisible = ref(false);
const checkForm = reactive({
  zt: "",
  month: "",
  ztValue: "",
  checkValue: "",
  ratio: "",
});
const checkRules = {
  zt: [{ required: true, message: "请选择载体", trigger: "change" }],
  month: [{ required: true, message: "请选择年月", trigger: "change" }],
  ztValue: [{ required: true, message: "请获取载体电量", trigger: "change" }],
  checkValue: [{ required: true, message: "请输入容量电量", trigger: "blur" }],
  ratio: [{ required: true, message: "请输入系数", trigger: "change" }],
};
const checkFormRef = ref();

function openCheckDialog() {
  checkForm.zt = "";
  checkForm.month = "";
  checkForm.ztValue = "";
  checkForm.checkValue = "";
  checkForm.ratio = "";
  checkDialogVisible.value = true;
}

// 选择载体或年月时获取载体电量
function handleCheckZtChange() {
  fetchZtValue();
}
function handleCheckMonthChange() {
  fetchZtValue();
}
function fetchZtValue() {
  if (checkForm.zt && checkForm.month) {
    getCarrierEnergy({ zt: checkForm.zt, month: checkForm.month }).then((res) => {
      checkForm.ztValue = res.data || "";
      calcCheckRatio();
    });
  } else {
    checkForm.ztValue = "";
    checkForm.ratio = "";
  }
}

// 输入容量电量时自动计算系数
function calcCheckRatio() {
  const ztValue = parseFloat(checkForm.ztValue);
  const checkValue = parseFloat(checkForm.checkValue);
  if (ztValue && checkValue) {
    checkForm.ratio = (checkValue / ztValue).toFixed(4);
  } else {
    checkForm.ratio = "";
  }
}

// 提交新增
function submitCheckForm() {
  console.log(checkForm);
  checkFormRef.value.validate((valid) => {
    if (!valid) return;
    addCheckEnergy({ ...checkForm }).then((res) => {
      if (res.code === 200) {
        checkDialogVisible.value = false;
        getCheckList();
      }
    });
  });
}

onMounted(() => {
  getMonthList();
  fetchCarrierList();
  getCheckList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.query-form {
  margin-bottom: 10px;
}
</style>
